<template>
  <div>
    <van-nav-bar
      @click-left="$router.go(-1)"
      left-arrow
      left-text="返回"
      title="登录"
    />
    <van-form
      :show-error="false"
      :show-error-message="false"
      @failed="onFailed"
      @submit="onSubmit"
      ref="vantLoginForm"
    >
      <van-cell-group>
        <!-- 输入手机号，调起手机号键盘 -->
        <van-field
          :maxlength="11"
          :rules="mobileRules"
          clearable
          name="mobile"
          placeholder="请输入手机号"
          type="tel"
          v-model="user.mobile"
        >
          <template #left-icon>
            <i class="iconfont icon-shouji" />
          </template>
        </van-field>
        <van-field
          :maxlength="6"
          :rules="codeRules"
          center
          clearable
          placeholder="请输入短信验证码"
          v-model="user.code"
        >
          <template #button>
            <van-button
              :disabled="isDisable"
              @click="getCode"
              native-type="button"
              size="small"
              type="primary"
            >{{isDisable?`${timeDown}s`:'获取验证码'}}</van-button>
          </template>
          <template #left-icon>
            <i class="iconfont icon-mima" />
          </template>
        </van-field>
      </van-cell-group>
      <div class="login-btn-wrap">
        <van-button
          block
          class="login-btn"
          type="info"
        >登录</van-button>
      </div>
    </van-form>
    <ul class="tip-info">
      <li>万能验证码: 246810</li>
      <li>如果未注册, 登录之后即注册成功</li>
      <li>测试账号: 13911111111 密码: 246810</li>
    </ul>
  </div>
</template>

<script>
import { login, sendCode } from "../../network/user";
import storage from "../../utils/storage";

export default {
  name: "Login",
  components: {},
  data() {
    return {
      user: {
        mobile: "",
        code: ""
      },
      mobileRules: [
        { required: true, message: "请填写手机号码" },
        { validator: this.mobileFun, message: "手机号格式错误" }
      ],
      codeRules: [{ required: true, message: "请填写验证码" }],
      isDisable: false,
      timeDown: 60
    };
  },
  methods: {
    //自定义手机验证函数
    mobileFun(val) {
      const regexp = new RegExp(/^1[3456789]\d{9}$/);
      return regexp.test(val);
    },
    //表单验证未通过
    onFailed(error) {
      this.$toast(error.errors[0].message);
    },
    //提交登录请求
    async onSubmit() {
      const result = await login(this.user);
      if (result.message === "OK") {
        this.$toast.success("登录成功");
        //成功后将token存储到本地和vuex容器中
        storage.setItem("USER_TOKEN", result.data);
        this.$store.commit("setUserToken", result.data);
        const redirect = this.$route.query.redirect;
        // console.log(redirect)
        if (redirect) {
          this.$router.push(`${redirect}`);
        } else {
          this.$router.push("/home");
        }
        // console.log(result)
        return;
      }
      this.$toast.fail("验证码错误");
    },
    //获取验证码
    async getCode() {
      try {
        //没有走catch函数就说明通过验证了，不需要获取结果
        await this.$refs.vantLoginForm.validate("mobile");
        //发送验证码
        const result = await sendCode(this.user.mobile);
        //禁用发送验证码按钮和开始倒计时
        if (result.message !== "OK") {
          if (result.response.status === 429) {
            this.$toast.fail("发送请求过于频繁");
          } else {
            this.$toast.fail("发送失败，请稍后再试");
          }
          return;
        }
        this.isDisable = true;
        const timer = setInterval(_ => {
          this.timeDown -= 1;
          if (this.timeDown === 0) {
            this.isDisable = false;
            clearTimeout(timer);
          }
        }, 1000);
      } catch (err) {
        this.$toast.fail(err.message);
      }
    }
  }
};
</script>

<style scoped lang="stylus">
.icon-shouji
  color #999

.login-btn
  width 90%
  margin 30px auto
  border-radius 4px

.tip-info
  color #666
  width 90%
  margin 50px auto 0

  li
    margin 5px 0
</style>